package com.xyhy.core.utils.id;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Random;

public interface SnowflakeId {
  Snowflake snowflake = IdUtil.getSnowflake(getWorkId(), 1);

  static Long getId() {
    return snowflake.nextId();
  }

  static int getHostId(String s, int max) {
    byte[] bytes = s.getBytes();
    int sums = 0;
    for (int b : bytes) {
      sums += b;
    }
    return sums % (max + 1);
  }

  /**
   * 根据host address取余，发送异常就获取0到31之间的随机数
   */
  static int getWorkId() {
    try {
      return getHostId(Inet4Address.getLocalHost().getHostAddress(), 31);
    } catch (UnknownHostException e) {
      return new Random().nextInt(32);
    }
  }

}
